package cn.mesmile.juc.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zb
 * @date 2021/8/17 14:29
 * @Description  读写锁
 */
public class ReadWriteLock {

    public static void main(String[] args) {
        MySource mySource = new MySource();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                final int n = i;
                mySource.read(n+"");
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                final int n = i;
                mySource.write(n+"",n);
            }
        },"A").start();

    }

}

class MySource {
    /** 公共资源 */
    private volatile Map<String, Object> map = new HashMap<>();
    /** 读写锁 */
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    public Object write(String key,Object value) {
        Object put = null;
        // 写锁
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" 正在写 "+ key);
            Thread.sleep(500);
            put = map.put(key, value);
            System.out.println(Thread.currentThread().getName()+" 写完了 "+ key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
        return put;
    }

    public Object read(String key) {
        Object o = null;
        // 读锁
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" 正在读 "+ key);
            Thread.sleep(300);
            o = map.get(key);
            System.out.println(Thread.currentThread().getName()+" 读完了 "+ key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
        return o;
    }

}
